<?php

	
	class Devmod_method_captcha extends Devmod_methods_abstraction {
		
		protected $after_operation = array(array(
										'for_method' => 'save',
										'for_method_type' => 'frontend_add',
										'use' => 'cp_verify'
									), array(
										'for_method' => 'export',
										'for_method_type' => 'frontend_add',
										'use' => 'cp_insert'
									));
		
		/**
		 * @param $args [array] 
		 * array (
		 * 	'length' => '6'
		 * )
		 */
		public function set_config($args)
		{
			if(!$this->helper->is_valid_config(array('length', 'font_size', 'text'), $args[0]))
			{
				// TODO: how to handle the error?
				echo "error!";
				exit;
			}
			$this->update_config('captcha', $args[0]);
			
			$this->cross_call('fields', array(array('captcha_img' => isset($args['title']) ? $args['title'] : 'Captcha')));			
		}
		
		public function cp_insert($args)
		{
			if(!isset($this->config[$this->type]['captcha'])) return $args;
			
			$random_string = Tools::RandomString($this->tmp_config['captcha']['length']);
			
			$_SESSION['captcha_config'] = array(
				'text' => $random_string,
				'font_size' => $this->tmp_config['captcha']['font_size']
			);
			
			$this->helper->array_push_associative($args, array(
				'captcha_img' => array(
					'<img src="'.SiteConfig::Domain.'share/files/captcha.php" border"0" />',
					$this->tmp_config['captcha']['text'],
					'<input type="text" name="captcha_img" value="" />'
				)
			));
			
			return $args;
		}
		
		public function cp_verify($args)
		{
			if(!isset($this->config[$this->type]['captcha'])) return $args;
			
			if(!isset($args['captcha_img'])) return false;
			
			if(empty($args['captcha_img'])) return false;
			
			if($_SESSION['captcha_config']['text'] !== $args['captcha_img']) return false;
			
			unset($args['captcha_img']);
			
			return $args;
		}
		
	
	}